using Microsoft.Extensions.Logging;
using Sage.Http.Authentication;
using Sage.Http.Configuration;
using Sage.Http.Exceptions;
using Sage.Http.Factory;
using Sage.Http.Handlers;
using Sage.Http.Models;
using Sage.Http.Options;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http.Headers;
using System.Runtime.CompilerServices;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.Json.Serialization.Metadata;
using System.Threading;
using System.Threading.Tasks;

namespace Sage.Http.Core
{
    /// <summary>
    /// 一个用于发送 HTTP 请求的辅助类，封装了常用的 HTTP 请求操作。
    /// 支持同步和异步方法。
    /// </summary>
    /// <remarks>
    /// 初始化HttpRequestManager实例
    /// </remarks>
    /// <param name="httpClient">HTTP客户端</param>
    /// <param name="logger">日志记录器（可选）</param>
    public class HttpRequestManager(HttpClient httpClient, ILogger? logger = null) : IHttpRequestManager
    {
        /// <summary>
        /// HttpClient 对象，用于发送 HTTP 请求。
        /// </summary>
        internal HttpClient? _client = httpClient ?? throw new ArgumentNullException(nameof(httpClient));
        /// <summary>
        /// 用于记录日志的Logger实例
        /// </summary>
        private readonly ILogger? _logger = logger;

        private readonly Lock _httpClientLock = new();

        // 认证所需
        private IAuthenticationProvider? _defaultAuthProvider;

        /// <summary>
        /// HTTP请求构建器工厂，负责创建请求构建器
        /// </summary>
        private readonly HttpRequestBuilderFactory _requestFactory = new(logger);

        private volatile bool _disposed = false;
        private readonly Lock _disposeLock = new();
        
        /// <summary>
        /// 初始化HttpRequestManager实例，带配置选项
        /// </summary>
        /// <param name="httpClient">HTTP客户端</param>
        /// <param name="logger">日志记录器（可选）</param>
        /// <param name="retryOptions">重试选项（可选）</param>
        /// <param name="circuitBreakerOptions">熔断选项（可选）</param>
        /// <param name="loggingOptions">日志选项（可选）</param>
        /// <param name="rateLimitOptions">限流选项（可选）</param>
        public HttpRequestManager(
            HttpClient httpClient, 
            ILogger? logger = null,
            RetryOptions? retryOptions = null,
            CircuitBreakerOptions? circuitBreakerOptions = null,
            LoggingOptions? loggingOptions = null,
            RateLimitOptions? rateLimitOptions = null) : this(httpClient, logger)
        {
            // 配置处理器管道
            ConfigureHandlers(retryOptions, circuitBreakerOptions, loggingOptions, rateLimitOptions);
        }
        
        /// <summary>
        /// 配置HTTP处理器管道
        /// </summary>
        private void ConfigureHandlers(
            RetryOptions? retryOptions = null,
            CircuitBreakerOptions? circuitBreakerOptions = null,
            LoggingOptions? loggingOptions = null,
            RateLimitOptions? rateLimitOptions = null)
        {
            if (_logger == null)
            {
                return; // 没有日志记录器，无法创建处理器
            }
            
            // 创建处理器链
            var handlers = new List<DelegatingHandler>();
            
            // 添加日志处理器
            if (loggingOptions?.LogRequests == true || loggingOptions?.LogResponses == true)
            {
                var loggingLogger = _logger as ILogger<LoggingHandler>;
                handlers.Add(new LoggingHandler(loggingLogger, loggingOptions));
            }
            
            // 添加限流处理器
            if (rateLimitOptions?.Enabled == true)
            {
                handlers.Add(new RateLimitHandler(rateLimitOptions, _logger));
            }
            
            // 添加重试处理器
            if (retryOptions?.Enabled == true)
            {
                handlers.Add(new RetryHandler(retryOptions, _logger));
            }
            
            // 添加熔断处理器
            if (circuitBreakerOptions?.Enabled == true)
            {
                handlers.Add(new CircuitBreakerHandler(circuitBreakerOptions, _logger));
            }
            
            // 配置处理器链
            if (handlers.Count > 0)
            {
                // 链接处理器
                for (int i = 0; i < handlers.Count - 1; i++)
                {
                    handlers[i].InnerHandler = handlers[i + 1];
                }
                
                // 最后一个处理器使用原始HttpClient的处理器
                var lastHandler = handlers[handlers.Count - 1];
                var innerHandler = _client?.GetType().GetProperty("Handler")?.GetValue(_client) as HttpMessageHandler 
                    ?? new HttpClientHandler();
                lastHandler.InnerHandler = innerHandler;
                
                // 创建新的HttpClient
                var newClient = new HttpClient(handlers[0])
                {
                    BaseAddress = _client?.BaseAddress,
                    Timeout = _client?.Timeout ?? TimeSpan.FromSeconds(100)
                };
                
                // 复制原始HttpClient的默认请求头
                if (_client != null)
                {
                    foreach (var header in _client.DefaultRequestHeaders)
                    {
                        newClient.DefaultRequestHeaders.TryAddWithoutValidation(header.Key, header.Value);
                    }
                }
                
                // 替换HttpClient
                _client = newClient;
            }
        }

        /// <summary>
        /// 设置默认认证提供者，将应用于所有请求
        /// </summary>
        /// <param name="authProvider">认证提供者</param>
        public void SetDefaultAuthentication(IAuthenticationProvider authProvider)
        {
            ArgumentNullException.ThrowIfNull(authProvider);
            
            _defaultAuthProvider = authProvider;
            _requestFactory.SetDefaultAuthentication(authProvider);
        }

        /// <summary>
        /// 设置Bearer Token认证
        /// </summary>
        /// <param name="token">认证令牌</param>
        /// <param name="scheme">认证方案，默认为"Bearer"</param>
        public void SetBearerToken(string token, string scheme = "Bearer")
        {
            ArgumentException.ThrowIfNullOrEmpty(token);
            
            SetDefaultAuthentication(new BearerTokenAuthProvider(token, scheme));
        }

        /// <summary>
        /// 设置Basic认证
        /// </summary>
        /// <param name="username">用户名</param>
        /// <param name="password">密码</param>
        public void SetBasicAuth(string username, string password)
        {
            ArgumentException.ThrowIfNullOrEmpty(username);
            ArgumentException.ThrowIfNullOrEmpty(password);
            
            SetDefaultAuthentication(new BasicAuthProvider(username, password));
        }

        /// <summary>
        /// 设置API Key认证
        /// </summary>
        /// <param name="apiKey">API密钥</param>
        /// <param name="parameterName">参数名称</param>
        /// <param name="location">密钥位置</param>
        public void SetApiKey(string apiKey, string parameterName, ApiKeyLocation location = ApiKeyLocation.Header)
        {
            ArgumentException.ThrowIfNullOrEmpty(apiKey);
            ArgumentException.ThrowIfNullOrEmpty(parameterName);
            
            SetDefaultAuthentication(new ApiKeyAuthProvider(apiKey, parameterName, 
                location == ApiKeyLocation.QueryParameter ? parameterName : null));
        }

        /// <summary>
        /// 释放HttpClient
        /// </summary>
        public void Dispose()
        {
            if (_disposed)
                return;

            lock (_disposeLock)
            {
                if (_disposed)
                    return;

                try
                {
                    _client?.Dispose();
                }
                catch (Exception ex)
                {
                    _logger?.LogWarning(ex, "释放 HttpClient 时出错");
                }
                finally
                {
                    _client = null;
                    _disposed = true;
                }
            }

            GC.SuppressFinalize(this);
        }

        /// <summary>
        /// 异步释放
        /// </summary>
        /// <returns></returns>
        public async ValueTask DisposeAsync()
        {
            if (_disposed)
                return;

            lock (_disposeLock)
            {
                if (_disposed)
                    return;
                _disposed = true;
            }

            if (_client is IAsyncDisposable asyncDisposable)
                await asyncDisposable.DisposeAsync().ConfigureAwait(false);
            else
                _client?.Dispose();

            _client = null;
            GC.SuppressFinalize(this);
        }

        // 在所有公共方法中添加检查
        private void ThrowIfDisposed()
        {
            ObjectDisposedException.ThrowIf(_disposed, this);
        }

        /// <summary>
        /// 提供一个方法在运行时更新 HttpClient
        /// </summary>
        /// <param name="newHttpClient">新的HttpClient实例</param>
        public void UpdateHttpClient(HttpClient newHttpClient)
        {
            ThrowIfDisposed();
            ArgumentNullException.ThrowIfNull(newHttpClient);

            lock (_httpClientLock)
            {
                if (_client != newHttpClient)
                {
                    // 可以根据需要处理旧的 HttpClient，例如调用 Dispose()
                    _client?.Dispose();
                    _client = newHttpClient;
                }
            }
        }

        /// <summary>
        /// 更新地址
        /// </summary>
        /// <param name="newUrl">新地址</param>
        /// <returns>是否成功更新</returns>
        public bool UpdateBaseAddress(Uri newUrl)
        {
            try
            {
                ArgumentNullException.ThrowIfNull(newUrl);
                ThrowIfDisposed();
                
                lock (_httpClientLock)
                {
                    if (_client == null)
                    {
                        throw new InvalidOperationException("HttpClient 未初始化。");
                    }
                    _client.BaseAddress = newUrl;
                }
                return true;
            }
            catch (Exception ex)
            {
                _logger?.LogError(ex, "更新BaseAddress失败: {Message}", ex.Message);
                return false;
            }
        }

        /// <summary>
        /// 更新地址
        /// </summary>
        /// <param name="newUrl">新地址</param>
        /// <param name="errorMessage">修改失败的错误原因</param>
        /// <returns>是否成功更新</returns>
        public bool UpdateBaseAddress(Uri newUrl, out string errorMessage)
        {
            errorMessage = string.Empty;
            try
            {
                ArgumentNullException.ThrowIfNull(newUrl);
                ThrowIfDisposed();
                
                lock (_httpClientLock)
                {
                    if (_client == null)
                    {
                        throw new InvalidOperationException("HttpClient 未初始化。");
                    }
                    _client.BaseAddress = newUrl;
                }
                return true;
            }
            catch (Exception ex)
            {
                errorMessage = $"更新BaseAddress失败: {ex.Message}";
                _logger?.LogError(ex, errorMessage);
                return false;
            }
        }

        /// <summary>
        /// 更新超时时间
        /// </summary>
        /// <param name="newTimeout">新时间</param>
        /// <returns>是否成功更新</returns>
        public bool UpdateTimeout(TimeSpan newTimeout)
        {
            try
            {
                ThrowIfDisposed();
                
                lock (_httpClientLock)
                {
                    if (_client == null)
                    {
                        throw new InvalidOperationException("HttpClient 未初始化。");
                    }
                    _client.Timeout = newTimeout;
                }
                return true;
            }
            catch (Exception ex)
            {
                _logger?.LogError(ex, "更新Timeout失败: {Message}", ex.Message);
                return false;
            }
        }

        /// <summary>
        /// 更新超时时间
        /// </summary>
        /// <param name="newTimeout">新时间</param>
        /// <param name="errorMessage">修改失败的错误原因</param>
        /// <returns>是否成功更新</returns>
        public bool UpdateTimeout(TimeSpan newTimeout, out string errorMessage)
        {
            errorMessage = string.Empty;
            try
            {
                ThrowIfDisposed();
                
                lock (_httpClientLock)
                {
                    if (_client == null)
                    {
                        throw new InvalidOperationException("HttpClient 未初始化。");
                    }
                    _client.Timeout = newTimeout;
                }
                return true;
            }
            catch (Exception ex)
            {
                errorMessage = $"更新Timeout失败: {ex.Message}";
                _logger?.LogError(ex, errorMessage);
                return false;
            }
        }

        /// <summary>
        /// 获取当前的 HttpClient对象
        /// </summary>
        protected HttpClient HttpClient
        {
            get
            {
                lock (_httpClientLock)
                {
                    if (_client == null)
                    {
                        throw new InvalidOperationException("HttpClient 未初始化。");
                    }
                    return _client;
                }
            }
        }

        /// <summary>
        /// BaseAddress地址
        /// </summary>
        public Uri? BaseAddress => _client?.BaseAddress;

        /// <summary>
        /// 为请求设置超时时间
        /// </summary>
        /// <param name="request">HTTP请求消息</param>
        /// <param name="timeout">超时时间</param>
        public static void SetRequestTimeout(HttpRequestMessage request, TimeSpan timeout)
        {
            HttpRequestBuilderFactory.SetRequestTimeout(request, timeout);
        }

        /// <summary>
        /// 配置全局JSON序列化选项
        /// </summary>
        /// <param name="options">要使用的JSON序列化选项</param>
        /// <exception cref="ArgumentNullException">选项为null时抛出</exception>
        public static void ConfigureJsonOptions(JsonSerializerOptions options)
        {
            JsonSerializerFactory.SetGlobalOptions(options);
        }

        /// <summary>
        /// 配置全局JSON序列化上下文（用于AOT兼容环境）
        /// </summary>
        /// <param name="context">要使用的JSON序列化上下文</param>
        /// <exception cref="ArgumentNullException">上下文为null时抛出</exception>
        public static void ConfigureJsonContext(JsonSerializerContext context)
        {
            JsonSerializerFactory.SetGlobalContext(context);
        }

        #region 构建器
        /// <summary>
        /// 创建HTTP请求构建器
        /// </summary>
        /// <param name="method">HTTP方法</param>
        /// <param name="url">请求URL</param>
        /// <returns>HTTP请求构建器</returns>
        public HttpRequestBuilder CreateRequest(HttpMethod method, string url)
        {
            return _requestFactory.CreateRequest(this, method, url);
        }

        /// <summary>
        /// 创建HTTP请求构建器，使用HttpRouteInfo对象指定API信息
        /// </summary>
        /// <param name="routeInfo">API路由信息</param>
        /// <returns>HTTP请求构建器</returns>
        /// <remarks>
        /// 如果<paramref name="routeInfo"/>的<see cref="HttpRouteInfo.UrlTemplate"/>包含格式化占位符（如"/api/users/{0}/orders/{1}"），
        /// 请确保在调用此方法前先调用<see cref="HttpRouteInfo.BuildUrl"/>方法提供实际参数，否则将使用未格式化的模板URL。
        /// </remarks>
        public HttpRequestBuilder CreateRequest(HttpRouteInfo routeInfo)
        {
            return _requestFactory.CreateRequest(this, routeInfo);
        }

        #endregion

        #region 异步方法



        /// <summary>
        /// 异步发送请求，此方法仅用于HttpRequestBuilder中
        /// </summary>
        /// <param name="request">HTTP请求消息</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>HTTP响应消息</returns>
        internal async Task<HttpResponseMessage> SendAsync(
            HttpRequestMessage request,
            CancellationToken cancellationToken = default)
        {
            return await SendRequestAsync(request, cancellationToken).ConfigureAwait(false);
        }

        /// <summary>
        /// 异步发送 HTTP 请求。
        /// </summary>
        /// <param name="method">HTTP 方法，例如 GET、POST 等。</param>
        /// <param name="url">请求的 URL。</param>
        /// <param name="queryParams">查询参数，可选。</param>
        /// <param name="body">请求体内容，可选。</param>
        /// <param name="bodyType">请求体类型，默认为 JSON。</param>
        /// <param name="headers">请求头，可选。</param>
        /// <param name="cancellationToken">取消令牌，可选。</param>
        /// <returns>返回异步操作任务，结果为 <see cref="HttpResponseMessage"/>。</returns>
        public async Task<HttpResponseMessage> SendAsync(
            HttpMethod method,
            string url,
            Dictionary<string, object>? queryParams = null,
            string? body = null,
            BodyType bodyType = BodyType.Json,
            Dictionary<string, object>? headers = null,
            CancellationToken cancellationToken = default)
        {
            // 调用内部通用方法
            return await SendInternalAsync(method: method, url: url, queryParams: queryParams, body: body, bodyType: bodyType, headers: headers, cancellationToken: cancellationToken).ConfigureAwait(false);
        }


        /// <summary>
        /// 异步发送 HTTP 请求，使用 <see cref="HttpRouteInfo"/> 对象指定 API 信息。
        /// </summary>
        /// <param name="routeInfo">API 路由信息。</param>
        /// <param name="queryParams">查询参数字典，可选。</param>
        /// <param name="body">请求体内容，可选。</param>
        /// <param name="bodyType">请求体类型，默认 JSON。</param>
        /// <param name="headers">请求头字典，可选。</param>
        /// <param name="cancellationToken">取消令牌。</param>
        /// <returns>异步操作，返回 <see cref="HttpResponseMessage"/>。</returns>
        public async Task<HttpResponseMessage> SendAsync(
            HttpRouteInfo routeInfo,
            Dictionary<string, object>? queryParams = null,
            string? body = null,
            BodyType bodyType = BodyType.Json,
            Dictionary<string, object>? headers = null,
            CancellationToken cancellationToken = default)
        {
            // 检查 apiRoute 是否为 null
            ArgumentNullException.ThrowIfNull(routeInfo);

            // 确定使用的 URL
            string url;
            if (!string.IsNullOrEmpty(routeInfo.Url))
            {
                // 如果已经调用了 BuildUrl，使用生成的 Url
                url = routeInfo.Url;
            }
            else
            {
                // 如果没有调用 BuildUrl，直接使用 UrlTemplate
                url = routeInfo.UrlTemplate;
            }

            // 调用已有的异步方法，传入 HttpMethod 和 URL
            return await SendAsync(
                method: routeInfo.Method,
                url: url,
                queryParams: queryParams,
                body: body,
                bodyType: bodyType,
                headers: headers,
                cancellationToken: cancellationToken).ConfigureAwait(false);
        }


        // ----- 添加便捷方法 -----

        /// <summary>
        /// 异步发送GET请求
        /// </summary>
        /// <param name="requestUri">请求URI</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>HTTP响应消息</returns>
        public async Task<HttpResponseMessage> GetAsync(string requestUri, CancellationToken cancellationToken = default)
        {
            ArgumentException.ThrowIfNullOrEmpty(requestUri);
            return await SendAsync(HttpMethod.Get, requestUri, cancellationToken: cancellationToken).ConfigureAwait(false);
        }

        /// <summary>
        /// 异步发送GET请求并返回字符串内容
        /// </summary>
        /// <param name="requestUri">请求URI</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>响应内容的字符串表示</returns>
        public async Task<string> GetStringAsync(string requestUri, CancellationToken cancellationToken = default)
        {
            using var response = await GetAsync(requestUri, cancellationToken).ConfigureAwait(false);
            response.EnsureSuccessStatusCode();
            return await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false);
        }

        /// <summary>
        /// 异步发送GET请求并返回字节数组
        /// </summary>
        /// <param name="requestUri">请求URI</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>响应内容的字节数组</returns>
        public async Task<byte[]> GetByteArrayAsync(string requestUri, CancellationToken cancellationToken = default)
        {
            using var response = await GetAsync(requestUri, cancellationToken).ConfigureAwait(false);
            response.EnsureSuccessStatusCode();
            return await response.Content.ReadAsByteArrayAsync(cancellationToken).ConfigureAwait(false);
        }

        /// <summary>
        /// 异步发送GET请求并返回流
        /// </summary>
        /// <param name="requestUri">请求URI</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>响应内容的流</returns>
        /// <remarks>
        /// 调用方负责释放返回的流。
        /// </remarks>
        public async Task<Stream> GetStreamAsync(string requestUri, CancellationToken cancellationToken = default)
        {
            // 注意：这里不使用using，因为我们要返回流
            var response = await GetAsync(requestUri, cancellationToken).ConfigureAwait(false);
            response.EnsureSuccessStatusCode();
            return await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
        }

        /// <summary>
        /// 异步发送POST请求
        /// </summary>
        /// <param name="requestUri">请求URI</param>
        /// <param name="content">请求内容</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>HTTP响应消息</returns>
        public async Task<HttpResponseMessage> PostAsync(
            string requestUri,
            HttpContent content,
            CancellationToken cancellationToken = default)
        {
            ArgumentException.ThrowIfNullOrEmpty(requestUri);
            ArgumentNullException.ThrowIfNull(content);

            var request = new HttpRequestMessage(HttpMethod.Post, requestUri)
            {
                Content = content
            };
            return await SendRequestAsync(request, cancellationToken).ConfigureAwait(false);
        }

        /// <summary>
        /// 异步发送PUT请求
        /// </summary>
        /// <param name="requestUri">请求URI</param>
        /// <param name="content">请求内容</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>HTTP响应消息</returns>
        public async Task<HttpResponseMessage> PutAsync(
            string requestUri,
            HttpContent content,
            CancellationToken cancellationToken = default)
        {
            ArgumentException.ThrowIfNullOrEmpty(requestUri);
            ArgumentNullException.ThrowIfNull(content);

            var request = new HttpRequestMessage(HttpMethod.Put, requestUri)
            {
                Content = content
            };
            return await SendRequestAsync(request, cancellationToken).ConfigureAwait(false);
        }

        /// <summary>
        /// 异步发送DELETE请求
        /// </summary>
        /// <param name="requestUri">请求URI</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>HTTP响应消息</returns>
        public async Task<HttpResponseMessage> DeleteAsync(
            string requestUri,
            CancellationToken cancellationToken = default)
        {
            ArgumentException.ThrowIfNullOrEmpty(requestUri);
            return await SendAsync(HttpMethod.Delete, requestUri, cancellationToken: cancellationToken).ConfigureAwait(false);
        }

        /// <summary>
        /// 异步发送PATCH请求
        /// </summary>
        /// <param name="requestUri">请求URI</param>
        /// <param name="content">请求内容</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>HTTP响应消息</returns>
        public async Task<HttpResponseMessage> PatchAsync(
            string requestUri,
            HttpContent content,
            CancellationToken cancellationToken = default)
        {
            ArgumentException.ThrowIfNullOrEmpty(requestUri);
            ArgumentNullException.ThrowIfNull(content);

            var request = new HttpRequestMessage(HttpMethod.Patch, requestUri)
            {
                Content = content
            };
            return await SendRequestAsync(request, cancellationToken).ConfigureAwait(false);
        }

        // ----- 添加流式API支持 -----

        /// <summary>
        /// 发送请求并作为异步枚举器获取流式响应
        /// </summary>
        /// <typeparam name="T">响应项类型</typeparam>
        /// <param name="method">HTTP方法</param>
        /// <param name="requestUri">请求URI</param>
        /// <param name="deserializer">自定义反序列化函数，如果为null则自动创建</param>
        /// <param name="jsonTypeInfo">JSON类型信息，用于AOT环境（推荐）</param>
        /// <param name="jsonOptions">自定义JSON序列化选项</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>响应项的异步枚举器</returns>
        /// <remarks>
        /// 此方法支持多种流式响应格式，包括Server-Sent Events (SSE)和JSON Lines。
        /// 
        /// 在AOT环境中，建议提供jsonTypeInfo参数以启用源生成序列化，例如：
        /// <code>
        /// await foreach (var item in client.GetStreamingAsync(method, uri, 
        ///     jsonTypeInfo: MyJsonContext.Default.MyType))
        /// {
        ///     // 处理数据
        /// }
        /// </code>
        /// </remarks>
        [RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed.")]
        [RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation.")]
        public async IAsyncEnumerable<T> GetStreamingAsync<T>(
            HttpMethod method,
            string requestUri,
            Func<string, T>? deserializer = null,
            JsonTypeInfo<T>? jsonTypeInfo = null,
            JsonSerializerOptions? jsonOptions = null,
            [EnumeratorCancellation] CancellationToken cancellationToken = default)
        {
            ArgumentNullException.ThrowIfNull(method);
            ArgumentException.ThrowIfNullOrEmpty(requestUri);

            HttpResponseMessage? response = null;
            Stream? stream = null;
            StreamReader? reader = null;

            try
            {
                var request = new HttpRequestMessage(method, requestUri);
                request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("text/event-stream"));

                response = await HttpClient.SendAsync(
                    request,
                    HttpCompletionOption.ResponseHeadersRead,
                    cancellationToken).ConfigureAwait(false);

                response.EnsureSuccessStatusCode();

                // 如果未提供反序列化函数，则创建一个
                deserializer ??= JsonSerializerFactory.CreateDeserializer(jsonTypeInfo, jsonOptions);

                stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
                reader = new StreamReader(stream);

                string? line;
                while ((line = await reader.ReadLineAsync(cancellationToken).ConfigureAwait(false)) != null)
                {
                    cancellationToken.ThrowIfCancellationRequested();

                    // 跳过空行
                    if (string.IsNullOrWhiteSpace(line))
                        continue;

                    // 提取并处理数据行
                    string dataContent = ExtractDataContent(line);
                    if (string.IsNullOrEmpty(dataContent))
                        continue;

                    // 处理数据行（避免yield return与try-catch冲突）
                    if (JsonSerializerFactory.TryDeserialize(dataContent, deserializer, out T? item) &&
                        item is not null)
                    {
                        yield return item;
                    }
                }
            }
            finally
            {
                // 按照创建的相反顺序释放资源
                reader?.Dispose();
                stream?.Dispose();
                response?.Dispose();
            }
        }

        /// <summary>
        /// 发送请求并作为异步枚举器获取流式响应（AOT 兼容版本）
        /// </summary>
        /// <typeparam name="T">响应项类型</typeparam>
        /// <param name="method">HTTP 方法</param>
        /// <param name="requestUri">请求 URI</param>
        /// <param name="jsonTypeInfo">JSON 类型信息，用于 AOT 环境</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>响应项的异步枚举器</returns>
        /// <remarks>
        /// 此方法是 AOT 兼容的，适用于需要源生成序列化的环境。
        /// </remarks>
        public async IAsyncEnumerable<T> GetStreamingAsync<T>(
            HttpMethod method,
            string requestUri,
            JsonTypeInfo<T> jsonTypeInfo,
            [EnumeratorCancellation] CancellationToken cancellationToken = default)
        {
            ArgumentNullException.ThrowIfNull(method);
            ArgumentException.ThrowIfNullOrEmpty(requestUri);
            ArgumentNullException.ThrowIfNull(jsonTypeInfo);

            var request = new HttpRequestMessage(method, requestUri);
            request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("text/event-stream"));

            // 使用内部方法处理流式响应
            await foreach (var item in ProcessStreamResponseAsync(request, jsonTypeInfo, cancellationToken))
            {
                yield return item;
            }
        }

        /// <summary>
        /// 向 HttpRequestBuilder 添加 AOT 兼容版本的流式处理方法
        /// </summary>
        /// <typeparam name="T">响应项类型</typeparam>
        /// <param name="request">HTTP 请求</param>
        /// <param name="jsonTypeInfo">JSON 类型信息</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>响应项的异步枚举器</returns>
        public async IAsyncEnumerable<T> SendAsStream<T>(
            HttpRequestMessage request,
            JsonTypeInfo<T> jsonTypeInfo,
            [EnumeratorCancellation] CancellationToken cancellationToken = default)
        {
            ArgumentNullException.ThrowIfNull(request);
            ArgumentNullException.ThrowIfNull(jsonTypeInfo);

            // 确保接受 SSE
            request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("text/event-stream"));

            // 使用内部方法处理流式响应
            await foreach (var item in ProcessStreamResponseAsync(request, jsonTypeInfo, cancellationToken))
            {
                yield return item;
            }
        }

        /// <summary>
        /// 处理流式响应的内部方法
        /// </summary>
        private async IAsyncEnumerable<T> ProcessStreamResponseAsync<T>(
            HttpRequestMessage request,
            JsonTypeInfo<T> jsonTypeInfo,
            [EnumeratorCancellation] CancellationToken cancellationToken = default)
        {
            // 发送请求并获取响应
            using var response = await SendRequestAsync(
                request,
                HttpCompletionOption.ResponseHeadersRead,
                cancellationToken).ConfigureAwait(false);

            response.EnsureSuccessStatusCode();

            // 获取响应流
            using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
            using var reader = new StreamReader(stream);

            string? line;
            while ((line = await reader.ReadLineAsync(cancellationToken).ConfigureAwait(false)) != null)
            {
                cancellationToken.ThrowIfCancellationRequested();

                // 跳过空行
                if (string.IsNullOrWhiteSpace(line))
                    continue;

                // 提取并处理数据行
                string dataContent = ExtractDataContent(line);
                if (string.IsNullOrEmpty(dataContent))
                    continue;

                // 尝试反序列化，安全处理异常
                T? item;
                try
                {
                    item = JsonSerializer.Deserialize(dataContent, jsonTypeInfo);
                }
                catch (JsonException ex)
                {
                    _logger?.LogWarning(ex, "JSON 反序列化错误: {Message}", ex.Message);
                    continue;
                }

                if (item is not null)
                {
                    yield return item;
                }
            }
        }

        /// <summary>
        /// 从响应行中提取数据内容
        /// </summary>
        private static string ExtractDataContent(string line)
        {
            // 检查是否为 SSE 格式的数据行 
            if (line.StartsWith("data:", StringComparison.OrdinalIgnoreCase))
            {
                return line[5..].Trim();
            }

            return line;
        }

        /// <summary>
        /// 发送请求并支持流式下载，报告进度
        /// </summary>
        /// <param name="method">HTTP方法</param>
        /// <param name="requestUri">请求URI</param>
        /// <param name="destination">目标流</param>
        /// <param name="progress">进度报告接口</param>
        /// <param name="bufferSize">缓冲区大小，默认81920字节(80KB)</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>下载的总字节数</returns>
        public async Task<long> DownloadAsync(
            HttpMethod method,
            string requestUri,
            Stream destination,
            IProgress<float>? progress = null,
            int bufferSize = 81920,
            CancellationToken cancellationToken = default)
        {
            ArgumentNullException.ThrowIfNull(method);
            ArgumentException.ThrowIfNullOrEmpty(requestUri);
            ArgumentNullException.ThrowIfNull(destination);

            if (!destination.CanWrite)
                throw new ArgumentException("目标流必须可写", nameof(destination));

            var request = new HttpRequestMessage(method, requestUri);

            // 使用ResponseHeadersRead选项，以便在接收到头信息后就返回响应
            HttpResponseMessage response;
            try
            {
                response = await HttpClient.SendAsync(
                    request,
                    HttpCompletionOption.ResponseHeadersRead,
                    cancellationToken).ConfigureAwait(false);

                response.EnsureSuccessStatusCode();
            }
            catch (Exception ex)
            {
                _logger?.LogError(ex, "下载请求发生错误: {Message}", ex.Message);
                throw;
            }

            try
            {
                var contentLength = response.Content.Headers.ContentLength;
                using var contentStream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);

                return await CopyStreamWithProgressAsync(
                    contentStream,
                    destination,
                    contentLength,
                    progress,
                    bufferSize,
                    cancellationToken).ConfigureAwait(false);
            }
            finally
            {
                // 确保响应被释放
                response.Dispose();
            }
        }

        /// <summary>
        /// 复制流并报告进度
        /// </summary>
        /// <param name="source">源流</param>
        /// <param name="destination">目标流</param>
        /// <param name="contentLength">内容长度，用于计算进度</param>
        /// <param name="progress">进度报告接口</param>
        /// <param name="bufferSize">缓冲区大小</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>复制的总字节数</returns>
        private static async Task<long> CopyStreamWithProgressAsync(
            Stream source,
            Stream destination,
            long? contentLength,
            IProgress<float>? progress,
            int bufferSize,
            CancellationToken cancellationToken)
        {
            ArgumentNullException.ThrowIfNull(source);
            ArgumentNullException.ThrowIfNull(destination);

            if (bufferSize <= 0)
                throw new ArgumentOutOfRangeException(nameof(bufferSize), "缓冲区大小必须大于0");

            var buffer = new byte[bufferSize];
            long totalBytesRead = 0;
            int bytesRead;

            // 报告初始进度
            progress?.Report(0);

            while ((bytesRead = await source.ReadAsync(buffer, cancellationToken).ConfigureAwait(false)) > 0)
            {
                await destination.WriteAsync(buffer.AsMemory(0, bytesRead), cancellationToken).ConfigureAwait(false);
                totalBytesRead += bytesRead;

                if (progress != null && contentLength.HasValue && contentLength.Value > 0)
                {
                    var progressValue = (float)totalBytesRead / contentLength.Value;
                    progress.Report(Math.Min(1.0f, progressValue)); // 确保不超过100%
                }

                cancellationToken.ThrowIfCancellationRequested();
            }

            // 确保最终进度为100%
            progress?.Report(1.0f);

            return totalBytesRead;
        }

        #endregion

        #region 同步方法

        /// <summary>
        /// 同步发送请求，此方法仅用于HttpRequestBuilder中
        /// </summary>
        /// <param name="request">HTTP请求消息</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>HTTP响应消息</returns>
        internal HttpResponseMessage Send(
            HttpRequestMessage request,
            CancellationToken cancellationToken = default)
        {
            return SendRequest(request, cancellationToken);
        }

        /// <summary>
        /// 同步发送 HTTP 请求。
        /// </summary>
        /// <param name="method">HTTP 方法，例如 GET、POST 等。</param>
        /// <param name="url">请求的 URL。</param>
        /// <param name="queryParams">查询参数，可选。</param>
        /// <param name="body">请求体内容，可选。</param>
        /// <param name="bodyType">请求体类型，默认为 JSON。</param>
        /// <param name="headers">请求头，可选。</param>
        /// <param name="cancellationToken">取消令牌，可选。</param>
        /// <returns>返回 <see cref="HttpResponseMessage"/>。</returns>
        public HttpResponseMessage Send(
            HttpMethod method,
            string url,
            Dictionary<string, object>? queryParams = null,
            string? body = null,
            BodyType bodyType = BodyType.Json,
            Dictionary<string, object>? headers = null,
            CancellationToken cancellationToken = default)
        {
            // 同步等待异步方法的结果
            return SendInternalAsync(method, url, queryParams, body, bodyType, headers, cancellationToken: cancellationToken)
                   .ConfigureAwait(false)
                   .GetAwaiter()
                   .GetResult();
        }

        /// <summary>
        /// 同步发送 HTTP 请求，使用 <see cref="HttpRouteInfo"/> 对象指定 API 信息。
        /// </summary>
        /// <param name="routeInfo">API 路由信息。</param>
        /// <param name="queryParams">查询参数字典，可选。</param>
        /// <param name="body">请求体内容，可选。</param>
        /// <param name="bodyType">请求体类型，默认 JSON。</param>
        /// <param name="headers">请求头字典，可选。</param>
        /// <param name="cancellationToken">取消令牌。</param>
        /// <returns>返回 <see cref="HttpResponseMessage"/>。</returns>
        public HttpResponseMessage Send(
            HttpRouteInfo routeInfo,
            Dictionary<string, object>? queryParams = null,
            string? body = null,
            BodyType bodyType = BodyType.Json,
            Dictionary<string, object>? headers = null,
            CancellationToken cancellationToken = default)
        {
            // 检查 apiRoute 是否为 null
            ArgumentNullException.ThrowIfNull(routeInfo);

            // 确定使用的 URL
            string url;
            if (!string.IsNullOrEmpty(routeInfo.Url))
            {
                // 如果已经调用了 BuildUrl，使用生成的 Url
                url = routeInfo.Url;
            }
            else
            {
                // 如果没有调用 BuildUrl，直接使用 UrlTemplate
                url = routeInfo.UrlTemplate;
            }

            // 调用已有的同步方法，传入 HttpMethod 和 URL
            return Send(
                method: routeInfo.Method,
                url: url,
                queryParams: queryParams,
                body: body,
                bodyType: bodyType,
                headers: headers,
                cancellationToken: cancellationToken);
        }
        #endregion

        #region 内部通用方法

        /// <summary>
        /// 使用指定的完成选项发送HTTP请求
        /// </summary>
        /// <param name="request">HTTP请求消息</param>
        /// <param name="completionOption">指定何时完成操作</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>HTTP响应消息</returns>
        internal async Task<HttpResponseMessage> SendRequestAsync(
            HttpRequestMessage request,
            HttpCompletionOption completionOption,
            CancellationToken cancellationToken = default)
        {
            ThrowIfDisposed();
            ArgumentNullException.ThrowIfNull(request);
            try
            {
                // 在发送请求前记录请求的详细信息
                await HttpRequestInfo(request).ConfigureAwait(false);
                // 发送 HTTP 请求并获取响应
                var response = await _client!.SendAsync(request, completionOption, cancellationToken);
                return response;
            }
            catch (OperationCanceledException ex) when (cancellationToken.IsCancellationRequested)
            {
                // 用户主动取消
                _logger?.LogWarning(ex, "请求已被用户取消");
                Debug.WriteLine("请求已被用户取消。");
                throw new HttpClientRequestException(HttpStatusCode.RequestTimeout, "请求已被用户取消", ex);
            }
            catch (OperationCanceledException ex)
            {
                // 超时导致的取消
                _logger?.LogWarning(ex, "请求超时");
                Debug.WriteLine("请求超时。");
                throw new HttpClientRequestException(HttpStatusCode.RequestTimeout, "请求超时", ex);
            }
            catch (HttpRequestException ex)
            {
                _logger?.LogError(ex, "HTTP请求错误: {Message}", ex.Message);
                Debug.WriteLine($"请求错误：{ex.Message}");
                throw new HttpClientRequestException(HttpStatusCode.ServiceUnavailable, "服务器暂时不可用，请稍后再试！", ex);
            }
            catch (TimeoutException ex)
            {
                _logger?.LogError(ex, "请求超时: {Message}", ex.Message);
                Debug.WriteLine($"请求超时：{ex.Message}");
                throw new HttpClientRequestException(HttpStatusCode.RequestTimeout, "请求超时", ex);
            }
            catch (Exception ex)
            {
                // 处理其他异常
                _logger?.LogError(ex, "请求失败: {Message}", ex.Message);
                Debug.WriteLine($"请求失败：{ex.Message}");
                throw new HttpClientRequestException(HttpStatusCode.InternalServerError, "请求失败", ex);
            }

        }

        /// <summary>
        /// 发送请求
        /// </summary>
        /// <param name="request">HTTP请求消息</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>HTTP响应消息</returns>
        private async Task<HttpResponseMessage> SendRequestAsync(
            HttpRequestMessage request,
            CancellationToken cancellationToken)
        {
            ThrowIfDisposed();
            ArgumentNullException.ThrowIfNull(request);

            try
            {
                // 在发送请求前记录请求的详细信息
                await HttpRequestInfo(request).ConfigureAwait(false);
                // 发送 HTTP 请求并获取响应
                var response = await _client!.SendAsync(request, cancellationToken).ConfigureAwait(false);
                return response;
            }
            catch (OperationCanceledException ex) when (cancellationToken.IsCancellationRequested)
            {
                // 用户主动取消
                _logger?.LogWarning(ex, "请求已被用户取消");
                Debug.WriteLine("请求已被用户取消。");
                throw new HttpClientRequestException(HttpStatusCode.RequestTimeout, "请求已被用户取消", ex);
            }
            catch (OperationCanceledException ex)
            {
                // 超时导致的取消
                _logger?.LogWarning(ex, "请求超时");
                Debug.WriteLine("请求超时。");
                throw new HttpClientRequestException(HttpStatusCode.RequestTimeout, "请求超时", ex);
            }
            catch (HttpRequestException ex)
            {
                _logger?.LogError(ex, "HTTP请求错误: {Message}", ex.Message);
                Debug.WriteLine($"请求错误：{ex.Message}");
                throw new HttpClientRequestException(HttpStatusCode.ServiceUnavailable, "服务器暂时不可用，请稍后再试！", ex);
            }
            catch (TimeoutException ex)
            {
                _logger?.LogError(ex, "请求超时: {Message}", ex.Message);
                Debug.WriteLine($"请求超时：{ex.Message}");
                throw new HttpClientRequestException(HttpStatusCode.RequestTimeout, "请求超时", ex);
            }
            catch (Exception ex)
            {
                // 处理其他异常
                _logger?.LogError(ex, "请求失败: {Message}", ex.Message);
                Debug.WriteLine($"请求失败：{ex.Message}");
                throw new HttpClientRequestException(HttpStatusCode.InternalServerError, "请求失败", ex);
            }
        }

        /// <summary>
        /// 同步发送请求
        /// </summary>
        /// <param name="request">HTTP请求消息</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>HTTP响应消息</returns>
        private HttpResponseMessage SendRequest(
            HttpRequestMessage request,
            CancellationToken cancellationToken)
        {
            ThrowIfDisposed();
            ArgumentNullException.ThrowIfNull(request);

            try
            {
                // 在发送请求前记录请求的详细信息
                HttpRequestInfoSync(request);

                // 发送 HTTP 请求并获取响应
                var response = _client!.Send(request, cancellationToken);

                return response;
            }
            catch (OperationCanceledException ex) when (cancellationToken.IsCancellationRequested)
            {
                // 用户主动取消
                _logger?.LogWarning(ex, "请求已被用户取消");
                Debug.WriteLine("请求已被用户取消。");
                throw new HttpClientRequestException(HttpStatusCode.RequestTimeout, "请求已被用户取消", ex);
            }
            catch (OperationCanceledException ex)
            {
                // 超时导致的取消
                _logger?.LogWarning(ex, "请求超时");
                Debug.WriteLine("请求超时。");
                throw new HttpClientRequestException(HttpStatusCode.RequestTimeout, "请求超时", ex);
            }
            catch (HttpRequestException ex)
            {
                _logger?.LogError(ex, "HTTP请求错误: {Message}", ex.Message);
                Debug.WriteLine($"请求错误：{ex.Message}");
                throw new HttpClientRequestException(HttpStatusCode.ServiceUnavailable, "服务器暂时不可用，请稍后再试！", ex);
            }
            catch (TimeoutException ex)
            {
                _logger?.LogError(ex, "请求超时: {Message}", ex.Message);
                Debug.WriteLine($"请求超时：{ex.Message}");
                throw new HttpClientRequestException(HttpStatusCode.RequestTimeout, "请求超时", ex);
            }
            catch (Exception ex)
            {
                // 处理其他异常
                _logger?.LogError(ex, "请求失败: {Message}", ex.Message);
                Debug.WriteLine($"请求失败：{ex.Message}");
                throw new HttpClientRequestException(HttpStatusCode.InternalServerError, "请求失败", ex);
            }
        }

        /// <summary>
        /// 内部通用方法，用于发送 HTTP 请求。
        /// </summary>
        /// <param name="method">HTTP 方法。</param>
        /// <param name="url">请求的 URL。</param>
        /// <param name="queryParams">查询参数。</param>
        /// <param name="body">请求体内容。</param>
        /// <param name="bodyType">请求体类型。</param>
        /// <param name="headers">请求头。</param>
        /// <param name="formData">表单字段。</param>
        /// <param name="files">文件数据。</param>
        /// <param name="progress">进度报告接口。</param>
        /// <param name="cancellationToken">取消令牌。</param>
        /// <returns>返回 <see cref="HttpResponseMessage"/>。</returns>
        public async Task<HttpResponseMessage> SendInternalAsync(
            HttpMethod method,
            string url,
            Dictionary<string, object>? queryParams,
            string? body,
            BodyType? bodyType,
            Dictionary<string, object>? headers = default,
            Dictionary<string, string>? formData = default,
            List<FileParameter>? files = default,
            IProgress<float>? progress = default,
            CancellationToken cancellationToken = default)
        {

            ThrowIfDisposed();

            if (_client == null)
            {
                throw new InvalidOperationException("HttpClient 尚未初始化。请先调用初始化！。");
            }
            try
            {
                // 构建完整的请求 URL，包括查询参数
                string requestUrl = HttpRequestBuilderFactory.BuildRequestUrl(url, queryParams);

                // 创建 HTTP 请求消息
                var request = new HttpRequestMessage(method, requestUrl);

                // 添加请求头（如果有）
                if (headers != null)
                {
                    HttpRequestBuilderFactory.AddHeaders(request, headers);
                }

                // 添加请求体内容（如果有）
                AddContent(request, body, bodyType: bodyType, formData, files, progress, cancellationToken);

                return await SendRequestAsync(request, cancellationToken).ConfigureAwait(false);
            }
            catch (Exception)
            {
                // 异常已在SendRequestAsync中处理和包装，这里直接抛出
                throw;
            }
        }

        #endregion

        #region 辅助方法

        /// <summary>
        /// 向 HTTP 请求添加请求体内容。
        /// </summary>
        /// <param name="request">HTTP 请求消息。</param>
        /// <param name="body">请求体字符串。</param>
        /// <param name="bodyType">请求体类型。</param>
        /// <param name="formData">表单字段（用于 MultipartFormData）。</param>
        /// <param name="files">文件数据（用于 MultipartFormData）。</param>
        /// <param name="progress">进度报告接口。</param>
        /// <param name="cancellationToken">取消令牌。</param>
        internal static void AddContent(
            HttpRequestMessage request,
            string? body,
            BodyType? bodyType,
            Dictionary<string, string>? formData = default,
            List<FileParameter>? files = default,
            IProgress<float>? progress = default,
            CancellationToken cancellationToken = default)
        {
            if (bodyType == BodyType.MultipartFormData)
            {
                var multipartContent = CreateMultipartContent(formData, files);

                request.Content = progress != null
                    ? new Content.ProgressableStreamContent(multipartContent, progress, cancellationToken: cancellationToken)
                    : multipartContent;
            }
            else if (!string.IsNullOrEmpty(body))
            {
                var stringContent = CreateStringContent(body, bodyType);

                request.Content = progress != null
                    ? new Content.ProgressableStreamContent(stringContent, progress, cancellationToken: cancellationToken)
                    : stringContent;
            }
        }

        /// <summary>
        /// 创建多部分表单内容
        /// </summary>
        /// <param name="formData">表单字段</param>
        /// <param name="files">文件列表</param>
        /// <returns>多部分表单内容</returns>
        internal static MultipartFormDataContent CreateMultipartContent(
            Dictionary<string, string>? formData,
            List<FileParameter>? files)
        {
            var multipartContent = new MultipartFormDataContent();

            // 添加表单字段
            if (formData != null)
            {
                foreach (var kvp in formData)
                {
                    multipartContent.Add(new StringContent(kvp.Value ?? string.Empty), kvp.Key);
                }
            }

            // 添加文件
            if (files != null)
            {
                foreach (var file in files)
                {
                    var fileContent = new StreamContent(file.Content);
                    fileContent.Headers.ContentType = new MediaTypeHeaderValue(file.ContentType);

                    fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
                    {
                        Name = file.FormFieldName != null ? $"\"{file.FormFieldName}\"" : "\"file\"",
                        FileName = $"\"{file.FileName}\""
                    };

                    multipartContent.Add(fileContent);
                }
            }

            return multipartContent;
        }

        /// <summary>
        /// 创建字符串内容
        /// </summary>
        /// <param name="body">请求体内容</param>
        /// <param name="bodyType">内容类型</param>
        /// <returns>字符串内容</returns>
        internal static StringContent CreateStringContent(string body, BodyType? bodyType)
        {
            string contentType = bodyType switch
            {
                BodyType.Json => "application/json",
                BodyType.Xml => "application/xml",
                BodyType.Form => "application/x-www-form-urlencoded",
                _ => "text/plain"
            };

            return new StringContent(body, Encoding.UTF8, contentType);
        }

        /// <summary>
        /// 输出请求的详细内容，包括请求行、请求头和请求体。
        /// </summary>
        /// <param name="request">HTTP 请求消息。</param>
        /// <returns>异步任务。</returns>
        internal async Task HttpRequestInfo(HttpRequestMessage request)
        {
            if (_logger == null || !_logger.IsEnabled(LogLevel.Debug))
            {
                return; // 如果没有日志记录器或日志级别不够，跳过详细日志记录
            }

            var output = new StringBuilder();

            // 记录请求方法和完整的请求 URI
            output.AppendLine($"{request.Method} {request.RequestUri} HTTP/{request.Version}");

            // 记录请求头
            foreach (var header in request.Headers)
            {
                // 敏感信息处理
                if (header.Key.Equals("Authorization", StringComparison.OrdinalIgnoreCase))
                {
                    output.AppendLine($"{header.Key}: Bearer ******");
                }
                else
                {
                    output.AppendLine($"{header.Key}: {string.Join(", ", header.Value)}");
                }
            }

            // 如果有内容，记录内容头和请求体
            if (request.Content != null)
            {
                foreach (var header in request.Content.Headers)
                {
                    output.AppendLine($"{header.Key}: {string.Join(", ", header.Value)}");
                }

                // 读取并记录请求体内容
                var body = await request.Content.ReadAsStringAsync().ConfigureAwait(false);

                // 限制内容大小，防止日志过大
                if (body.Length > 4000)
                {
                    body = string.Concat(body.AsSpan(0, 4000), "... [内容已截断]");
                }

                output.AppendLine();
                output.AppendLine(body);
            }

            // 输出记录的信息
            _logger.LogDebug("请求内容:\n{RequestDetails}", output);
            Debug.Print($"请求内容:\n{output}");
        }

        /// <summary>
        /// 同步记录HTTP请求信息
        /// </summary>
        /// <param name="request">HTTP请求</param>
        internal void HttpRequestInfoSync(HttpRequestMessage request)
        {
            if (_logger == null || !_logger.IsEnabled(LogLevel.Debug))
            {
                return; // 如果没有日志记录器或日志级别不够，跳过详细日志记录
            }

            var output = new StringBuilder();

            // 记录请求方法和完整的请求 URI
            output.AppendLine($"{request.Method} {request.RequestUri} HTTP/{request.Version}");

            // 记录请求头
            foreach (var header in request.Headers)
            {
                // 敏感信息处理
                if (header.Key.Equals("Authorization", StringComparison.OrdinalIgnoreCase))
                {
                    output.AppendLine($"{header.Key}: Bearer ******");
                }
                else
                {
                    output.AppendLine($"{header.Key}: {string.Join(", ", header.Value)}");
                }
            }

            // 如果有内容，记录内容头
            if (request.Content != null)
            {
                foreach (var header in request.Content.Headers)
                {
                    output.AppendLine($"{header.Key}: {string.Join(", ", header.Value)}");
                }

                // 对于同步方法，我们不读取请求体内容以避免潜在的流消耗问题
                output.AppendLine();
                output.AppendLine("[请求体内容在同步模式下不记录]");
            }

            // 输出记录的信息
            _logger.LogDebug("请求内容:\n{RequestDetails}", output);
            Debug.Print($"请求内容:\n{output}");
        }

        #endregion

        /// <summary>
        /// 使用请求选项创建HTTP请求构建器
        /// </summary>
        /// <param name="method">HTTP方法</param>
        /// <param name="url">请求URL</param>
        /// <param name="options">请求选项</param>
        /// <returns>HTTP请求构建器</returns>
        public HttpRequestBuilder CreateRequestWithOptions(HttpMethod method, string url, RequestOptions options)
        {
            ThrowIfDisposed();
            ArgumentNullException.ThrowIfNull(options);

            var builder = CreateRequest(method, url);
            options.ApplyTo(builder);
            return builder;
        }

        /// <summary>
        /// 使用请求选项创建HTTP请求构建器，使用HttpRouteInfo对象指定API信息
        /// </summary>
        /// <param name="routeInfo">API路由信息</param>
        /// <param name="options">请求选项</param>
        /// <returns>HTTP请求构建器</returns>
        public HttpRequestBuilder CreateRequestWithOptions(HttpRouteInfo routeInfo, RequestOptions options)
        {
            ThrowIfDisposed();
            ArgumentNullException.ThrowIfNull(routeInfo);
            ArgumentNullException.ThrowIfNull(options);

            var builder = CreateRequest(routeInfo);
            options.ApplyTo(builder);
            return builder;
        }

        /// <summary>
        /// 创建专用于JSON请求的构建器
        /// </summary>
        /// <param name="method">HTTP方法</param>
        /// <param name="url">请求URL</param>
        /// <returns>HTTP请求构建器</returns>
        public HttpRequestBuilder CreateJsonRequest(HttpMethod method, string url)
        {
            ThrowIfDisposed();
            return CreateRequest(method, url)
                .WithHeader("Accept", "application/json");
        }

        /// <summary>
        /// 使用请求选项创建专用于JSON请求的构建器
        /// </summary>
        /// <param name="method">HTTP方法</param>
        /// <param name="url">请求URL</param>
        /// <param name="options">请求选项</param>
        /// <returns>HTTP请求构建器</returns>
        public HttpRequestBuilder CreateJsonRequest(HttpMethod method, string url, RequestOptions options)
        {
            ThrowIfDisposed();
            ArgumentNullException.ThrowIfNull(options);

            var builder = CreateJsonRequest(method, url);
            options.ApplyTo(builder);
            return builder;
        }
    }
}